package photobox

//import com.drew.imaging.ImageMetadataReader
//import com.drew.metadata.exif.ExifSubIFDDirectory
import com.sun.image.codec.jpeg.JPEGCodec
import grails.converters.JSON
import photobox.account.Address
import photobox.account.Member
import photobox.account.Region
import photobox.account.User
import photobox.account.UserBrowse
import photobox.photo.Category
import photobox.photo.Photo
import photobox.order.Order
import photobox.photo.PhotoComment
import photobox.photo.PhotoFrame
import photobox.photo.PhotoPaper
import photobox.photo.PhotoSize
import photobox.utils.ImageUtils
import javax.imageio.ImageIO
import java.awt.image.BufferedImage
import java.text.SimpleDateFormat


//import com.drew.metadata.Directory;
//import com.drew.metadata.Metadata;



class PhotoController extends BaseController {
    def photoService

    def  test(){
        def targetImg
        def pressImg
        def pressText
        def fontName
        //File f = new File(this.getClass().getResource("/").getPath());System.out.println(f);
        println( resource(dir: '/assets/img', file: 'logo.png'))
        targetImg = resource(dir: '/web-app/assets/img', file: 'watermark.png')
        pressImg = "D://2014-04-05-11-24_800.jpg"
        pressText= "美丽"

//        File jpegFile = new File("D://withExif.JPG");
//        Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
//        println('sssss')
//        println(metadata)
//        println(44444)
//        Directory directory = metadata.getDirectory(ExifSubIFDDirectory.class);
//        println(directory)

//        directory.tags.each {
//            println(it.tagName)
//            println(it.tagType)
//            println(it.tagTypeHex)
//           println(it.description)
//
//        }

            //ImageUtils.pressImage("","",1000,1000)
        ImageUtils.pressImage(targetImg,pressImg,0,0)

        ImageUtils.pressText(pressText,pressImg,fontName,100,100,100,100,100)

        //ImageUtils.pressText("","","",100,100,100,100,100)



        /* def photohql="SELECT COUNT(*) FROM `pht_photo` WHERE  date_created=\"2014-12-05 10:25:45\" "
         def photo=Photo.executeQuery(photohql)
         if(photo<30){
             println("继续上传")
         }else{
             println("122121122121")
         }*/
    }

    def updateLaud(){
        def member = Member.get(session.userId)
        def photo = Photo.get(params.id)
        def userBrowse = UserBrowse.findByUserAndPhoto(member, photo)
        if (userBrowse.laud == 0) {
            userBrowse = photoService.updateLaudNum(member, photo)
            render ([status:0,message:'updateLaud',laudNum:userBrowse.photo.laudNum] as JSON)
        }else {
            render ([status:1,message:'isLaud',laudNum:userBrowse.photo.laudNum] as JSON)
        }
     }


    def save() {

        String pictureUrl=uploadImage()//调用上传图片的方法，返回一个储//存图片的路径。
        println(pictureUrl)

        //render([status:1,msg:"ok", img:pictureUrl] as JSON)
        render([status:1,msg:"ok", img:pictureUrl] as JSON)
    }
    def uploadImage(){//上傳圖片到本地文件夾中
        BufferedImage
        ImageIO
        JPEGCodec
        def filePathName
        def path
        def f = request.getFile ('file')//获取前台页面表单控//中的文件名称
        String pictureUrl =  request.getSession().getServletContext().getRealPath('images');
        if (!f.empty) {
            Date  d= new Date();
            String dateString=  d.format ("yyyy-mm-dd-hh-ss")
            String  fileProName=f.getOriginalFilename ()
            String extension = fileProName.split('\\.')[-1]  //截取获取文0. //件名的后缀
            filePathName = pictureUrl+"/" + dateString+"."+extension


//            println(filePathName)
//            File jpegFile = new File(filePathName);
//            Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
//            Directory directory = metadata.getDirectory(ExifSubIFDDirectory.class);
//            def digiTime = ''
//            directory.tags.each {
//                println(it)
//               if(it.tagName == 'Date/Time Original') {
//                   digiTime = it.description
//               }
//            }

            f.transferTo (new File(filePathName))
//            def targetImg = resource(dir: '/web-app/assets/img', file: 'watermark.png')        水印图片
            ImageUtils.makeSmallImage(filePathName,   pictureUrl+"/"+dateString+"_800."+extension ,800)
//            ImageUtils.pressImage(targetImg,pictureUrl+"/"+dateString+"_800."+extension,0,0)
            ImageUtils.makeSmallImage(pictureUrl+"/"+dateString+"_800."+extension,   pictureUrl+"/"+dateString+"_400."+extension ,400)
            ImageUtils.makeSmallImage(pictureUrl+"/"+dateString+"_800."+extension,   pictureUrl+"/"+dateString+"_200."+extension ,200)


//            ImageUtils.pressImage(targetImg,pictureUrl+"/"+dateString+"_400."+extension,0,0)
//            ImageUtils.pressImage(targetImg,pictureUrl+"/"+dateString+"_200."+extension,0,0)

            path = [ originImagePath:"images/"+dateString+"."+extension, smallImagePath:"images/"+dateString+"_200."+extension, middleImagePath:"images/"+dateString+"_400."+extension,bigImagePath:"images/"+dateString+"_800."+extension ]
//            path = [originImagePath:"images/"+dateString+"."+extension]
        }
        /*
            String      originImagePath    //原图路径
            String      smallImagePath    //小图路径200px
            String      middleImagePath   //中图400px
            String      bigImagePath      //大图800px
         */
        render(path as JSON)  //返回文件名称
    }
    def add(){
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }
        def photoSizeList = PhotoSize.findAll()
        def category = photobox.photo.Category.findAll()
        def isOrNo = [
                [id:Photo.ISDEAL_YES,text:'是'],
                [id:Photo.ISDEAL_NO,text:'否']
        ]
        //计算用户本月上传作品数量
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        def mList = Photo.findAll(" from Photo where date_created like '"+df.format(new Date()).toString()+"%' and user_id="+session.userId)
        println(mList.size())

        [photoSize:photoSizeList,category:category,isOrNo:isOrNo,mPhoteSize:mList.size()]
    }
    def create(){
       def member = Member.get(session.userId)
        photoService.createPhoto(params, member)
        redirect(controller:"photo",action: "uploadSuccess")
    }
    def uploadSuccess(){
        if(session.userId==null){
            redirect(controller: "home" ,action:"index")
        }
    }
    def show(){
        def userBrowse
        def member = Member.get(session.userId)
        def photo = Photo.get(params.id)
        //其他相似作品
        def hqlC = "SELECT P from Photo as P join P.categories as C where C.id=:categoryId and P <> :photo order by P.dateCreated desc"
        def similarPhotos = Photo.executeQuery(hqlC, ['categoryId': photo.categories[0].id,'photo':photo], [max: 5])
        //评论
        //def photoComment = PhotoComment.findAllByPhoto(photo,[sort:dateCreated,order:'desc'])
        def photoComment = PhotoComment.findAll("from PhotoComment as P where P.photo=:photo order by P.dateCreated desc",[photo:photo])
        //赞
        if (member) {
            def hql = "from UserBrowse as B where B.user.id = :userId and B.photo.id = :photoId"
            def result = UserBrowse.executeQuery(hql, [userId: member.id, photoId: photo.id])
            if (result) {
                userBrowse = photoService.updateUserBrowse(member, photo)
            }else {
                userBrowse = photoService.createUserBrowse(member, photo)
            }
        }
        //更多该作者作品
        def photoOwner = Photo.findAll('from Photo as P where P.user=:user and P <> :photo order by P.dateCreated desc',[user: photo.user,'photo':photo],[max: 3])
        def photoNum = Photo.countByUser(photo.user)
        //作品主题风格
        def theme = []
//        def themeId = []
        def style = []
//        def styleId = []
        photo.categories.each {
            if(it.categoryType == 1) {
                theme.push([name:it.name,id: it.id])
            }else if(it.categoryType == 2) {
//                style.push(it.name)
//                  styleId.push(it.id)
                style.push([name:it.name,id: it.id])
            }
        }

        [ photoComment:photoComment,photo:photo,userBrowse:userBrowse, photoOwner:photoOwner,similarPhotos:similarPhotos,photoNum:photoNum,theme:theme,style:style/*,themeId:themeId,styleId:styleId*/]
      }


    def listByCity() {

        render g.select(name: "city", id: "form-city", optionKey: "id", optionValue: "name", class: "width-50",
                from: Region.findAllByPid(params.provinceId),
                noSelection: ["":"--请选择--"],
                onchange: remoteFunction(controller: 'photo', action: 'listByDistrict', params: '\'cityId=\'+this.value', update: 'district')) + "市"
    }

    def listByDistrict() {
        render g.select(name: "district", id: "form-district", optionKey: "id", optionValue: "name", class: "width-50",
                from: Region.findAllByPid(params.cityId),
                noSelection: ["":"--请选择--"]) + "区(县)"
    }

    // 分类详情页
    def categoryDetail() {
        def categoryName = Category.get(params.id)?.name?Category.get(params.id)?.name:params.searchKey
        def hql_t = "from Category as C where C.categoryType = 1"
        def categories_theme = Category.findAll(hql_t)
        def hql_s = "from Category as C where C.categoryType = 2"
        def categories_style = Category.findAll(hql_s)
        def category = Category.get(params.id)
        if(params.json) {
            def max = params.max?:8
            def offset = params.offset?:0

            // def hql="from CityInfo where id>:id  and code in:code"
            // def result=CityInfo.executeQuery(hql,["id":2,code:["NB","NJ"]])
            def hql = " from Photo as P join P.categories as C where C.id=:categoryId order by P.dateCreated desc"
            def photoList = Photo.executeQuery(hql, ['categoryId': category.id], [max: max, offset: offset])
            def photoLists = []
            photoList.each{
                photoLists.push(
                        id: it[0].id,
                        smallImagePath: it[0].smallImagePath,
                        name: it[0].name,
                        price: it[0].price,
                        username: it[0].user?.username
                )
            }
            def o = max.toInteger() +  offset.toInteger()
            def total = Photo.executeQuery("select count(*)" + hql, ['categoryId':category.id])
            render ([photoList: photoLists, total: total, offset: o,max:max,categoryId:category.id] as JSON)
        }
        [categories_theme: categories_theme,categories_style:categories_style,category: category, categoryName:categoryName,categoryId:category.id]
    }

    // 全站检索（作品）
    def searchByStation() {
//        for (i in 1..200) {
//            def date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
//            def now = new Date()
//            def photo = new Photo()
//            photo.name = "风景随拍"
//            photo.keywords = "风景随拍"
//            photo.description = "....."
//            photo.isDeal = 0
//            photo.originImagePath = "....."
//            photo.smallImagePath = "....."
//            photo.laudNum = 0
//            photo.shareNum = 0
//            photo.saleNum = 0
//            photo.price = 0.00
//            photo.device = "for"
//            photo.picTime = date.parse(date.format(now))
//            photo.user = User.get(4)
//            if (!photo.save()) {
//                throw new grails.validation.ValidationException("创建照片时发生错误", photo.errors)
//            }
//
//        }

        def max = params.max?:10
        def offset = params.offset?:0
        def hql = "from Photo as P where P.keywords like :keyword"
        def keyword = "%" + params.searchKey + "%"
        def keywordText = params.searchKey
        //def photoList = Photo.findAllByKeywordsLike(keyword, [max:max, offset:offset])
        def photoList = Photo.executeQuery(hql, ['keyword':keyword], [max:max, offset:offset])
        def photoLists = []
        photoList.each{
            photoLists.push(
                    id: it.id,
                    smallImagePath: it.smallImagePath,
                    name: it.name,
                    price: it.price,
                    username: it.user?.username
            )
        }
        def total = Photo.countByKeywordsLike(keyword)
        def o = max.toInteger() +  offset.toInteger()
        if(params.searchBtn){
            [photoList: photoLists, total: total,searchKey:keywordText, offset: o,max:max]
        }else if(params.offset){
            render ([photoList: photoLists, total: total,searchKey:keywordText, offset: o,max:max] as JSON)
        }
    }
    def morePhoto() {
        if(params.json) {
            def max = params.max?:10
            def offset = params.offset?:0
            def hql
            if(params.id == 'new'){
                hql = "from Photo as P order by P.dateCreated desc"
            }else if(params.id == 'recommend'){
                hql = "from Photo as P where P.isRecommend = 1"
            }
            def photoList = Photo.executeQuery(hql,  [max:max, offset:offset])
            def photoLists = []
            photoList.each{
                photoLists.push(
                        id: it.id,
                        smallImagePath: it.smallImagePath,
                        name: it.name,
                        price: it.price,
                        username: it.user?.username
                )
            }
            def o = max.toInteger() +  offset.toInteger()
            render ([photoList: photoLists,  offset: o,max:max,newId:params.id] as JSON)
        }
        [newId:params.id]
    }

    def createComment(){
        def user = User.get(session.userId)
        def photoComment =  photoService.createComment(params,user)
        def photoImage = user.photoImage
        def commentDate = photoComment.dateCreated.format("yyyy-MM-dd HH:mm:ss")
        def commentPerson = photoComment.user.username
        render ([message:'success',photoComment:photoComment.comment,photoImage:photoImage,commentPerson:commentPerson,commentDate:commentDate] as JSON)
    }
    //PhotoBox用户使用协议
    def procotol(){
    }

    // 排行榜详情页
    def listDetails() {
        if(params.json) {
            def max = params.max
            def offset = params.offset

            def calendar  =   new  GregorianCalendar()
            calendar.set(GregorianCalendar.DAY_OF_MONTH, 1);
            def beginTime = calendar.getTime();
            def condition = new HashMap()
            condition['dateCreated'] = beginTime

            def hql = ""
            def photoList = []
            def photoLists = []

            if(params.name == 'totalBestSell'){
                hql = "from Photo as P order by saleNum desc"
                photoList = Photo.executeQuery(hql, [], [max:max, offset:offset])
                photoLists = []
                photoList.each{
                    photoLists.push(
                            id: it.id,
                            smallImagePath: it.smallImagePath,
                            middleImagePath:it.middleImagePath,
                            showShape:it.showShape,
                            name: it.name,
                            price: it.price,
                            username: it.user?.username,
                            laudNum:it.laudNum,
                            saleNum:it.saleNum
                    )
                }
            }else if(params.name == 'monthBestSell') {
                hql = " from Order as O join O.items as OI WHERE O.dateCreated >= :dateCreated GROUP BY OI.photo.id ORDER BY SUM(OI.number) DESC "
                def orders = Order.executeQuery("select OI " +hql,condition, [max:max, offset:offset])
                orders.each {
                    photoLists.push(
                            id: it.photo.id,
                            smallImagePath: it.photo.smallImagePath,
                            middleImagePath:it.photo.middleImagePath,
                            showShape:it.photo.showShape,
                            name: it.photo.name,
                            price: it.photo.price,
                            username: it.photo.user?.username,
                            laudNum:it.photo.laudNum,
                            saleNum:it.photo.saleNum
                    )
                }
            }else if(params.name == 'totalBestLaud') {
                hql = "from Photo as P order by laudNum desc"
                photoList = Photo.executeQuery(hql, [], [max:max, offset:offset])
                photoLists = []
                photoList.each{
                    photoLists.push(
                            id: it.id,
                            smallImagePath: it.smallImagePath,
                            middleImagePath:it.middleImagePath,
                            showShape:it.showShape,
                            name: it.name,
                            price: it.price,
                            username: it.user?.username,
                            laudNum:it.laudNum,
                            saleNum:it.saleNum
                    )
                }
            }else if(params.name == 'monthBestLaud') {
                hql = " select P from UserBrowse as UB join UB.photo as P WHERE UB.lastUpdated >= :dateCreated AND UB.laud = 1 GROUP BY P ORDER BY SUM(UB.laud) DESC"
                def laudPhotos = Order.executeQuery(hql,condition, [max:max, offset:offset])
                laudPhotos.each {
                    photoLists.push(
                            id: it.id,
                            smallImagePath: it.smallImagePath,
                            middleImagePath:it.middleImagePath,
                            showShape:it.showShape,
                            name: it.name,
                            price: it.price,
                            username: it.user?.username,
                            laudNum:it.laudNum,
                            saleNum:it.saleNum
                    )
                }
            }
            //def photoList = Photo.findAllByKeywordsLike(keyword, [max:max, offset:offset])

            def o = max.toInteger() +  offset.toInteger()
            render( [photoList:photoLists, offset: o,max:max,rank:params.name] as JSON)
        }
        [rank:params.name]
    }

    def bestPhotographer(){
        if(params.json) {
            def max = params.max
            def offset = params.offset
            def hql = ""
            def photographerList = []

            if(params.name == 'totalBestPhotographer') {
                hql = "select P.user from Photo as P GROUP BY P.user order by SUM(P.saleNum) desc"
                photographerList = Photo.executeQuery(hql, [], [max: max, offset: offset])
            }else if(params.name == 'monthBestPhotographer'){
                def calendar  =   new  GregorianCalendar()
                calendar.set(GregorianCalendar.DAY_OF_MONTH, 1);
                def beginTime = calendar.getTime();
                def condition = new HashMap()
                condition['dateCreated'] = beginTime

                hql = " from Order as O join O.items as OI WHERE O.dateCreated >= :dateCreated GROUP BY OI.photo.id ORDER BY SUM(OI.number) DESC "
                photographerList = Order.executeQuery("select distinct OI.photo.user " +hql,condition, [max:max, offset:offset])

            }
            def o = max.toInteger() +  offset.toInteger()
            render( [photographerList:photographerList,rank:params.name, offset: o,max:max] as JSON)
        }
        [rank:params.name]
    }

}
